<?php

namespace plugin\ai\app\controller;

use Exception;
use Intervention\Image\ImageManagerStatic as Image;
use support\Request;
use support\Response;

class UploadController
{

    /**
     * 头像设置
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function avatar(Request $request): Response
    {
        $file = $request->file('avatar');
        if ($file && $file->isValid()) {
            $ext = strtolower($file->getUploadExtension());
            if (!in_array($ext, ['jpg', 'jpeg', 'gif', 'png'])) {
                return json(['code' => 2, 'msg' => '仅支持 jpg jpeg gif png格式']);
            }
            $image = Image::make($file);
            $width = $image->width();
            $height = $image->height();
            $size = min($width, $height);
            $image->crop($size, $size)->resize(80, 80);
            $relativePath = 'upload/avatar';
            $realPath = base_path("/plugin/ai/public/$relativePath");
            if (!is_dir($realPath)) {
                mkdir($realPath, 0777, true);
            }
            $name = bin2hex(pack('Nn', time(), random_int(0, 65535))) . ".$ext";
            $url = "/app/ai/$relativePath/$name";
            $path = "$realPath/$name";
            $image->save($path);
            return json(['code' => 0, 'msg' => 'upload success', 'data' => ['url' => $url]]);
        }
        return json(['code' => 1, 'msg' => 'file not found']);
    }

}
